<?php
// +----------------------------------------------------------------------
// | OpenSociax [ open your team ! ]
// +----------------------------------------------------------------------
// | Copyright (c) 2010 http://www.sociax.com.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: genixsoft.net <智士软件>
// +----------------------------------------------------------------------
// $Id$

/**
 +------------------------------------------------------------------------------
 * 附件操作服务，参考XattachModel
 +------------------------------------------------------------------------------
 */

//载入附件Track数据模型（需要保存的数据）
require_cache('./addons/models/XattachModel.class.php');

//载入上传操作类
require_cache("./addons/libs/Think/UploadFile.class.php");

class XattachService extends Service {
	var $site	=	'';	//获取站点设置
	/**
     +----------------------------------------------------------
     * 架构函数
     +----------------------------------------------------------
     * @author melec制作
     * @access public
     +----------------------------------------------------------
     */
    public function __construct($text) {
		$this->site	=	model('Xdata')->lget('site');
		//1.判断是否安装、是否运行该服务，系统服务可以不做判断
		//2.服务初始化
		$this->init($text);
		$this->run();
    }

	//服务初始化
	public function init($text=''){

	}

	//运行服务
	public function run(){

	}
	
	//上传附件
	public function upload($attach_type='attach',$input_options=array()){

		//载入默认规则
		$default_options	=	array();
		$default_options['custom_path']	=	date('Y/md/H/');	//应用定义的上传目录规则
		$default_options['max_size']	=	($this->site['attach_size'])?$this->site['attach_size'].'M':'20M';				//默认附件大小20兆
		$default_options['allow_exts']	=	($this->site['attach_type'])?$this->site['attach_type']:'jpg,gif,png,bmp,doc,ppt,zip,rar';	//默认类型
		$default_options['allow_types']	=	'';
		$default_options['save_path']	=	UPLOAD_PATH.'/'.$default_options['custom_path'];
		$default_options['save_name']	=	'';
		$default_options['save_rule']	=	'uniqid';
		$default_options['save_to_db']	=	true;
		$default_options['limit']       =   0;
		
		//创建目录
		mkdir($default_options['save_path'],0777,true);
		chmod($default_options['save_path'],0777);

		//对$input_options进行过滤，增强安全性
		//定制化设这 覆盖默认设置
		//$options	=	array_merge($default_options,$input_options);
		$options	=	$default_options;
		$options['allow_exts']	=	implode(',',array_intersect(explode('',$input_options['allow_exts']),explode(',',$default_options['allow_exts'])));

		if($input_options['save_name']){
			$options['save_name']	=	$input_options['save_name'];
		}
		if($input_options['save_path']){
			$options['save_path']	=	$input_options['save_path'];
		}
		
		//用户ID
		if( intval($options['uid'])==0 )	$options['uid']	=	intval($_SESSION['mid']);
		
		//初始化上传参数
        $upload					=	new UploadFile($options['max_size'],$options['allow_exts'],$options['allow_types']);

		//设置上传路径
		$upload->savePath		=	$options['save_path'];

        //启用子目录
		$upload->autoSub		=	false;

		//保存的名字
        $upload->saveName		=   $options['save_name'];

		//默认文件名规则
		$upload->saveRule		=	$options['save_rule'];

        //是否缩略图
        $upload->thumb          =   false;

		//执行上传操作
        if(!$upload->upload()) {

			//上传失败，返回错误
			$return['status']	=	false;
			$return['info']		=	$upload->getErrorMsg();

		}else{

			//获取成功上传的细心
			$upload_info	=	$upload->getUploadFileInfo();

			//保存上传的附件信息到数据库
			$infos	=	$this->saveToDb($attach_type,$upload_info,$options);
			//输出信息
			$return['status']	=	true;
			$return['info']		=	$infos;

    	}

		return	$return;
	}
	
	//获取文件流
	public function streamUpload() {
	
	}

	private function parseOption($option) {
		return $option;
	}

	//将信息保存到附件表中
	private function saveToDb($attach_type='attach',$upload_info=array(),$options=array()) {
		//保存信息到附件表
		if($options['save_to_db']){
			foreach($upload_info as $u){
				$map['attach_type']	=	$attach_type;
				$map['uid']			=	$options['uid'];
				$map['name']		=	$u['name'];
				$map['type']		=	$u['type'];
				$map['size']		=	$u['size'];
				$map['extension']	=	$u['extension'];
				$map['hash']		=	$u['hash'];
				$map['savepath']	=	$options['custom_path'];
				$map['savename']	=	$u['savename'];
				//$map['savedomain']=	C('ATTACH_SAVE_DOMAIN');
				$aid				=	model('Xattach')->add($map);
				$map['id']			=	intval($aid);
				$map['key']			=	$u['key'];
				$infos[]			=	$map;
				unset($map);
			}
		}else{
			$infos	=	$upload_info;
		}
		return $infos;
	}

	//下载附件
	public function download($aid){
		if(intval($aid) == 0){
			$aid	=	intval($_REQUEST['id']);
		}
		//if(intval($uid) == 0){
		//	$uid	=	intval($_REQUEST['uid']);
		//}
		$attach	=	model('Xattach')->where("id='$aid'")->find();
		if(!$attach){
			$this->error('附件不存在或已被删除！');
		}
		//下载函数
		//import("ORG.Net.Http");             //调用下载类
		require_cache('./addons/libs/Think/Http.class.php');
		if(file_exists(UPLOAD_PATH.$attach['savepath'].$attach['savename'])) {
			$filename = $attach['name'];
			$filename = auto_charset($filename,"UTF-8",'GB2312');
			Http::download(UPLOAD_PATH.$attach['savepath'].$attach['savename'],$filename);
		}else{
			$this->error('附件不存在或已被删除！');
		}
	}
	
	/* 后台管理相关方法 */

	//返回失败信息
	public function error($info,$return=false){
		$output['status']	=	false;
		$output['info']		=	$info;
		if($return){
			return $output;
		}else{
			echo json_encode($output);
		}
	}
	
	//返回成功信息
	public function success($info,$return=false){
		$output['status']	=	true;
		$output['info']		=	$info;
		if($return){
			return $output;
		}else{
			echo json_encode($output);
		}
	}
	
	//返回附件数据
	public function getAttach($attachId) {
		if(!is_array($attachId)){
			$attachId	=	explode(',',$attachId);
		}
		foreach($attachId as $v){
			$attachIds[]	=	intval($v);	
		}
		$map['id']	=	array('in',$attachIds);
		return model('Xattach')->where($map)->findAll();
	}

	//返回附件数据
	public function checkAttach($attachId) {
		if(!is_array($attachId)){
			$attachId	=	explode(',',$attachId);
		}
		foreach($attachId as $v){
			$attachIds[]	=	intval($v);	
		}
		$map['id']	=	array('in',$attachIds);
		$attaches	=	model('Xattach')->where($map)->findAll();
		if(!$attaches){
			return '';
		}else{
			foreach($attaches as $v){
				$return	.=	$v['id'].',';	
			}
		}
		return rtrim($return,',');
	}

	//启动服务，未编码
	public function _start(){
		return true;
	}
	
	//停止服务，未编码
	public function _stop(){
		return true;
	}

	//卸载服务，未编码
	public function _install(){
		return true;
	}

	//卸载服务，未编码
	public function _uninstall(){
		return true;
	}

}
?>